
import requests
import time
import os

def check_smartbox_online(cnt):
    ret = 0
    url = "http://127.0.0.1:9999/hi"
    # url = "http://192.168.104.125:9999/hi"
    try:
        res = requests.get(url, timeout=5)
    except:
        print("error")
        ret = -1
    if ret == 0 and res.status_code != 200: ret = -1
    if ret == 0: return
    if cnt > 0: 
        os.system("reboot")

    time.sleep(2)
    os.system("kill -9 `pgrep smartbox`")
    os.system("nohup ./smartbox 1 2>&1 &")

def check_frpc_online():
    ret = os.system("pgrep frpc")
    if ret == 0: return
    
    time.sleep(2)
    os.system("systemctl start frpc.service")

def check_mediaserver_online():
    ret = os.system("pgrep MediaServer")
    if ret == 0: return
    
    time.sleep(2)
    os.system("systemctl start media_kit.service")


def daemon():
    time.sleep(30)
    cnt = 0
    while True:
        time.sleep(5)
        # ret = check_mediaserver_online()
        # ret = check_frpc_online()

        ret = check_smartbox_online(cnt)
        cnt+=1
        time.sleep(30)
        
if __name__ == "__main__":
    daemon()
